package mk.com.ldm.corepoint.implementation.client.presenter;

import java.util.HashMap;

import mk.com.ldm.corepoint.implementation.client.CoreServiceAsync;
import mk.com.ldm.corepoint.implementation.client.lib.custom.cpstable.CustomPagingScrollTable;
import mk.com.ldm.corepoint.implementation.client.lib.generators.FormGenerator;
import mk.com.ldm.corepoint.implementation.client.view.ModalOverlay;
import mk.com.ldm.corepoint.implementation.shared.FormObject;

import org.gwt.mosaic.ui.client.InfoPanel;
import org.gwt.mosaic.ui.client.WindowPanel;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class EditPresenter implements Presenter {
	
	private CoreServiceAsync rpcService;
	private HandlerManager eventBus;
	private Display display;
	private String type;
	private String objectName;
	private FormGenerator formGenerator;
	private String itemId;
	private String name;
	private TextBox listViewTextBox = new TextBox();
	private String listViewReturn;
	private String historyToken;
	private CustomPagingScrollTable table;
		
	public interface Display{
		void setForm(Widget form);
		void setForm(Widget form, String buttonText);
		Button getReportButton();
		WindowPanel getWindow();
		Widget asWidget();
		ListBox getPageType();
	}

	public EditPresenter(CoreServiceAsync rpcService, HandlerManager eventBus, Display view, String type, String objectName, String itemId, String name){
	  	this.rpcService = rpcService;
	    this.eventBus = eventBus;
	    this.display = view;
	    this.type = type;
	    this.itemId = itemId;
	    this.objectName = objectName;
	    this.name = name;
	    if(this.itemId != null){
	    	  this.formGenerator = new FormGenerator(eventBus, display.getWindow(), "update");
	    } else {
	    	  this.formGenerator = new FormGenerator(eventBus, display.getWindow(), "insert");
	    }
	}
	
	public EditPresenter(CoreServiceAsync rpcService, HandlerManager eventBus, Display view, String historyToken){
		this.rpcService = rpcService;
	    this.eventBus = eventBus;
	    this.display = view;
	    this.historyToken = historyToken;
	}
	
	public Display getDisplay(){
		return display;
	}
	
	public FormGenerator getFormGenerator(){
		return formGenerator;
	}
	
	public void setListViewTextBox(TextBox tb){
		listViewTextBox = tb;
	}
	
	public void setListViewReturn(String ret){
		listViewReturn = ret;
	}
	
	
	public void bind(){
		display.getReportButton().addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				generateReport();
			}
		});
	}
	
	public void go(final HasWidgets container) {
		
		if(itemId!=null){
			getFilledForm(objectName,itemId);
		} else if(historyToken != null) {
			getReportTable(historyToken);
		} else {
			getForm(type,objectName);
		}
	}
	
	public void go(){
		display.getWindow().show();
	}

	public void getForm(String type, final String objectName){
		rpcService.parseConfigObject(Cookies.getCookie("username"), objectName, "Form", name, new AsyncCallback<FormObject>() {
			
			@Override
			public void onSuccess(FormObject result) {
				HashMap<String, String> params = new HashMap<String, String>();
				if(listViewReturn!=null){
					params.put("listViewReturn",listViewReturn);
					params.put("username", Cookies.getCookie("username"));
					params.put("objectName", objectName);
					params.put("type", "List");
					params.put("name", name);
				}
				formGenerator.setParams(params);
				display.setForm(formGenerator.generateForm(result));
				formGenerator.getFirst().setFocus(true);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				InfoPanel.show("Error", "Failed to communicate with the server.");
			}
		});
	}
	
	public void getFilledForm(String objectName, String id){
		rpcService.fetchConfigObject(objectName, itemId, "Form", name, new AsyncCallback<FormObject>(){

			@Override
			public void onFailure(Throwable caught) {
				InfoPanel.show("Error", "Failed to communicate with the server.");
			}

			@Override
			public void onSuccess(FormObject result) {
				display.setForm(formGenerator.generateForm(result));
				formGenerator.getFirst().setFocus(true);
			}
			
		});
	}
	
	
	public void getReportTable(String token){
		table = new CustomPagingScrollTable();
		table.setType(CustomPagingScrollTable.REPORT);
		table.setInitialUse(true);
		table.setRpcService(rpcService);
		table.setUsername(Cookies.getCookie("username"));
		table.setObjectName(token.split("/")[0]);
		table.setObjectType(token.split("/")[1]);
		table.setName("Report");
		table.getTable().setHeight("200px");
		table.fillTable();
		display.getWindow().setCaption(token.split("/")[0]+" report generation");
		display.setForm(table, "Save "+token.split("/")[0]+" report");
		bind();
	}

	public void generateReport(){
		ModalOverlay.show();
		rpcService.generateReport(Cookies.getCookie("username"), table.getObjectName(), table.getObjectType(), table.getName(), table.getOrder(), table.getFilters(), table.getReportVisibleColumns(), Integer.parseInt(display.getPageType().getValue(display.getPageType().getSelectedIndex())) , new AsyncCallback<String> (){

			@Override
			public void onFailure(Throwable caught) {
				InfoPanel.show("Server","Failed to communicate with the server.");
				ModalOverlay.hide();
			}

			@Override
			public void onSuccess(String result) {
				InfoPanel.show("Server", "Report saved.");
				ModalOverlay.hide();
				HTMLPanel html = new HTMLPanel("<iframe style='width:1024px; height:768px;'' src='http://docs.google.com/viewer?url="+Window.Location.getHostName()+"/reports/"+result+"' />");
				html.setHeight("768px");
				html.setWidth("1024px");
				WindowPanel window = new WindowPanel();
				window.add(html);
				window.pack();
				window.setHeight("768px");
				window.setWidth("1024px");
				window.center();
				window.show();
			}
			
		});
	}
	
}
